import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { environment } from '@env/environment';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { SystemDictService } from '../service/service.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-children-edit',
  templateUrl: './children-edit.component.html',
  styles: [],
})
export class SystemChildrenDictEditComponent implements OnInit {
  @Input()
  record: any;
  @Input()
  code: any;
  @Input()
  parentId: any;
  yesOrNo = environment.yesNo;
  form: FormGroup;
  constructor(
    private systemDictService: SystemDictService,
    private fb: FormBuilder,
    private modal: NzModalRef,
    private message: NzMessageService,
  ) {
    this.form = this.fb.group({
      id: [null],
      isRun: [null, [Validators.required]],
      dictValue: [null, [Validators.required]],
      dictKey: [null, [Validators.required]],
    });
  }

  ngOnInit(): void {
    if (this.record) {
      this.form.patchValue(this.record);
    }
  }

  save() {
    const isValid = this.validate();
    if (!isValid) {
      this.message.create('error', ' 请填写必填内容！');
      return;
    }

    const postData = {
      ...this.form.value,
      code: this.code,
      parentId: this.parentId,
    };

    this.systemDictService.submit(postData).subscribe(() => {
      this.close(true);
    });
  }

  close(fg?: boolean) {
    this.modal.close(fg);
  }

  validate() {
    for (const key in this.form.controls) {
      if (this.form.controls.hasOwnProperty(key)) {
        const element = this.form.controls[key];
        element.markAsDirty();
        element.updateValueAndValidity();
      }
    }
    return this.form.valid;
  }
}
